#!/usr/bin/env python3

"""Replace BEND tags with bilingual annotations inside Markdown outlines.

Examples:
    python replace_tags.py OutlineV1.md
    python replace_tags.py --encoding gb18030 Report_OutlineV1.md

If no file is provided, the script defaults to `Report_OutlineV1.md` in the same
directory as this script.
"""

from __future__ import annotations

import argparse
import re
from pathlib import Path

MAPPING = {
    "Back": "支持领袖",
    "Build": "建立社群",
    "Bridge": "连接社群",
    "Boost": "扩大社群",
    "Neutralize": "削弱领袖",
    "Nuke": "摧毁社群",
    "Narrow": "分裂社群",
    "Neglect": "边缘化社群",
    "Engage": "情感共鸣",
    "Explain": "解释说明",
    "Excite": "激发情绪",
    "Enhance": "强化信息",
    "Dismiss": "否定议题",
    "Distort": "扭曲事实",
    "Dismay": "煽动恐惧",
    "Distract": "转移话题",
}

DEFAULT_FILE = Path(__file__).resolve().parent / "Report_OutlineV1.md"


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Replace BEND tags with bilingual annotations."
    )
    parser.add_argument(
        "filepath",
        nargs="?",
        default=str(DEFAULT_FILE),
        help="要处理的 Markdown 文件路径（默认：Report_OutlineV1.md）",
    )
    parser.add_argument(
        "--encoding",
        default="utf-8",
        help="文件编码（默认：utf-8）。",
    )
    return parser.parse_args()


def process_file(path: Path, encoding: str) -> None:
    if not path.exists():
        raise SystemExit(f"找不到目标文件：{path}")

    content = path.read_text(encoding=encoding)
    total_replacements = 0
    for tag, translation in MAPPING.items():
        replacement = f"{tag}（{translation}）"
        pattern = re.compile(rf"{re.escape(tag)}（[^）]*）")
        content, count = pattern.subn(replacement, content)
        if count:
            total_replacements += count
            print(f"{tag}: {count} 处已替换")

    if total_replacements:
        path.write_text(content, encoding=encoding)
        print(f"完成，共替换 {total_replacements} 处标签。")
    else:
        print("未发现可替换的标签。")


def main() -> None:
    args = parse_args()
    target_path = Path(args.filepath).expanduser()
    process_file(target_path.resolve(), encoding=args.encoding)


if __name__ == "__main__":
    main()

